<template>
<div class="address flex-column">

    <div class="form-box flex-1">
        
        <template v-if="list.length === 0">
            <van-empty image="search" description="您还未添加收货地址" />
        </template>
        <template v-else>
            <div class="address_box flex-center pl15 pr15" v-for="item in list" :key="item.id">
                <div class="flex-1 text-left pr10" @click="selectChange(item.id)">
                    <div>
                        <span class="blod">{{ item.name }}</span>
                        <span class="ml10 mr10">{{ item.phone }}</span>
                        <van-tag plain type="danger" v-if="item.is_default === 1">默认</van-tag>
                    </div>
                    <div class="fz-12 ellipsis-2" style="color: #666">
                        {{ item.addr }} {{ item.addr_extra }}
                    </div>
                </div>
                <div class="fz-26">
                    <van-icon name="edit" @click="$router.push(`/address-edit?id=${item.id}`)" />
                    <van-icon name="delete-o" class="ml20" @click="deletAddress(item.id)"></van-icon>
                </div>
            </div>

        </template>
    </div>

    <div class="footer flex-center height-58">
        <van-button type="danger" round size="small" @click="$router.push('/address-edit')"> 新增地址 </van-button>
    </div>

</div>
</template>

<script>
export default {
    data () {
        return {
            list: []
        }
    },
    methods: {
        selectChange (id) { // 选择提交订单地址
            if (!this.$route.query.redirect && this.$route.query.redirect !== 'checkout') return
            const address = this.list.find(item => item.id === id)
            this.$store.commit('user/setDefaultAddress', address)
            this.$router.back()
        },
        deletAddress (id) {
            this.$dialog.confirm({ message: '确认删除当前选中地址？', title: '提示' }).then(() => {
                this.$user.delAddress(id).then(res => {
                    this.$toast('地址已删除')
                    this.getAddress()
                })
            })
        },
        // 获取 收货 地址 list
        getAddress () {
            this.$user.getAddressList().then(res => {
                this.list = res.data.list
                // if (res.data.list.length > 0) {
                //     const address = res.data.list.find(item => item.is_default === 1)
                //     if (!address) {
                //         this.$store.commit(res.data.list[0])
                //     } else {
                //         this.$store.commit('user/setDefaultAddress', address)
                //     }
                // }
            })
        }
    },
    created () {
        this.getAddress()
    }
}
</script>

<style lang="less" scoped>
.address_box {
    height: 70px;
    background-color: #fff;
    margin-bottom: 10px;
}
.footer {
    background-color: #fff;
}
</style>
